<template>
  <div class="app-container">
    <!-- 搜索框、过滤框 -->
    <div class="filter-container">
      <!-- listQuery 封装查询条件对象，@keyup.enter.native 是ele封装的 @keyup.enter 方法， handleFilter 是查询操作-->
      <el-input v-model="listQuery.workpieceId" placeholder="工件ID" clearable style="width: 180px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.workpieceName" placeholder="工件名称" clearable style="width: 180px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <!-- @change 表示下拉菜单的选值改变，并且不同的 brandId 和 seriesId 有关联，一一对应-->
      <el-select v-model="listQuery.workpieceCategoryId" class="filter-item" clearable placeholder="类别"
        style="width: 180px;" @keyup.enter.native="handleFilter">
        <!-- 工件类目列表 options，字典数组，键值对格式-->
        <el-option v-for="item in options" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId" />
      </el-select>
      <el-select v-model="listQuery.processFlexibility" placeholder="加工柔性" clearable class="filter-item" style="width: 120px"
        @keyup.enter.native="handleFilter">
        <!-- 工件柔性加工信息 carStatusOptions -->
        <el-option v-for="item in workpieceProcessFlexibleOptions" :key="item.key" :label="item.display_name"
          :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.workpieceStatus" placeholder="状态" clearable class="filter-item" style="width: 120px"
        @keyup.enter.native="handleFilter">
        <!-- 工件态信息 workpieceStatusOptions -->
        <el-option v-for="item in workpieceStatusOptions" :key="item.key" :label="item.display_name"
          :value="item.key" />
      </el-select>
      <!-- v-waves 样式点击出现水波纹 type 控制按钮颜色-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button v-waves class="filter-item" type="success" icon="el-icon-circle-plus-outline"
        @click="handleAddWorkpiece">增加</el-button>
      <!-- :loading 表示 , handleDownload 表示处理下载-->
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>
    <!-- v-loading 实现加载效果，sort-change 是排序改变的两个小箭头，与 sortable 配合使用-->
    <!-- sort-change -->
    <el-table v-loading="listLoading" :key="tableKey" :data="list" fit highlight-current-row style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="工件ID" prop="workpieceId" sortable="custom" align="center" min-width="105px">
        <!-- 作用域插槽，父组件调用了名为 scope 的坑，并且向里面填充了 <span></span> 标签, 固定用法 scope.row 获取 数组 data 中的数据-->
        <template slot-scope="scope">
          <span>{{ scope.row.workpieceId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="名称" align="center" min-width="215px">
        <template slot-scope="scope">
          <span>{{ scope.row.workpieceName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="样式图" align="center" min-width="75px">
        <template slot-scope="scope">
          <span>{{ scope.row.workpieceImg }}</span>
        </template>
      </el-table-column>

      <el-table-column label="类别" align="center" min-width="105px">
        <template slot-scope="scope">
          <!-- 此处显示的不是类别的 id，而是类别的名称 -->
          <!--  -->
          <span>{{ categoryFilter(scope.row.workpieceCategoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售卖价格" sortable="custom" prop="workpiecePrice" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>￥ {{ scope.row.workpiecePrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工序个数" sortable="custom" prop="processNum" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>{{ scope.row.processNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加工柔性" class-name="status-col" min-width="90px">
        <template slot-scope="scope">
          <!-- 添加标签过滤器 typeFilter 将数字转化为文字显示 displayDescription 用作鼠标移动获取详情-->
          <el-popover placement="top-start" title="工件工艺流程：" width="200" trigger="click"
            :content="scope.row.processInfo">
            <el-button :type="scope.row.processFlexibility | statusFilter4Flexibility" plain slot="reference" size="small ">{{
              scope.row.processFlexibility | typeFilter4Flexibility }}</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" min-width="90px">
        <template slot-scope="scope">
          <!-- 添加标签过滤器 typeFilter 将数字转化为文字显示 displayDescription 用作鼠标移动获取详情-->
          <el-popover placement="top-start" title="工件详情：" width="200" trigger="click"
            :content="scope.row.workpieceDescription">
            <el-button :type="scope.row.workpieceStatus | statusFilter" plain slot="reference" size="small ">{{
              scope.row.workpieceStatus | typeFilter }}</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updatedTime" sortable="custom" min-width="135px" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <!-- 加入管理员权限判断，此处需要 admin 权限，从全局加载的 store 中读取登录者权限，局部控制显示与否-->
      <!-- checkPermission(['admin']) -->
      <el-table-column v-if="true" label="操作" align="center" min-width="80px">
        <template slot-scope="scope">
          <!-- handleUpdate(scope.row) 将这行的数据传入函数 handleUpdate 中 -->
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码显示分页标签： 双向绑定->:limit.sync 每页显示的条数 :page.sync 页码 @pagination 类似于 change 事件，当页码或者每页条数发生改变时候触发 getList 事件-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
    <!-- 编辑功能的权限判断 v-if，:visible.sync 表示是否显示表单 -->
    <!-- checkPermission(['admin']) -->
    <el-dialog v-if="true" :visible.sync="dialogFormVisible" title="更改工件信息">
      <!-- rules 表示绑定输入数据的规则，:model 表示绑定一个数据对象 -->
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <!-- 一条数据 prop 为 temp 中的一条数据，用于回显-->
        <!--  -->
        <!--  -->

        <el-form-item label="类别" prop="category">
          <el-input v-model="temp.category" style="width: 220px" :disabled="true" />
        </el-form-item>

        <el-form-item label="名称" prop="workpieceName">
          <el-input v-model="temp.workpieceName" />
        </el-form-item>

        <el-form-item label="样式图" prop="workpieceImg">
          <el-input v-model="temp.workpieceImg" />
        </el-form-item>

        <el-form-item label="售卖价格" prop="workpiecePrice">
          <el-input v-model.number="temp.workpiecePrice" />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="temp.workpieceStatus" class="filter-item" >
            <el-option v-for="item in workpieceStatusOptions" :key="item.key" :label="item.display_name"
              :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="workpieceDescription">
          <el-input v-model="temp.workpieceDescription" type="textarea" placeholder="请输入描述信息" rows="5" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>

    <!-- 增加工件的表单填写 -->
    <el-dialog v-if="true" :visible.sync="addDialogFormVisible" title="增加工件">
      <el-form ref="addDataForm" :rules="rules" :model="temp" label-position="right" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="workpieceName">
          <el-input v-model="temp.workpieceName" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="temp.workpieceCategoryId" class="filter-item" clearable 
            style="width: 180px;">
            <el-option v-for="item in options" :key="item.categoryId" :label="item.categoryName"
              :value="item.categoryId" />
          </el-select>
          <el-button type="success" icon="el-icon-circle-plus-outline" @click="handleAddCategory">增加</el-button>
          <!-- 增加添加工件类别功能 -->
        </el-form-item>
        <el-form-item label="样式图" prop="workpieceImg">
          <el-input v-model="temp.workpieceImg" />
        </el-form-item>
        <el-form-item label="售卖价格" prop="workpiecePrice">
          <el-input v-model.number="temp.workpiecePrice" />
        </el-form-item>
        <el-form-item label="状态" required>
          <el-select v-model="temp.workpieceStatus" class="filter-item" >
            <el-option v-for="item in workpieceStatusOptions" :key="item.key" :label="item.display_name"
              :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="工序个数" prop="processNum" required>
          <el-input v-model.number="temp.processNum" />
        </el-form-item>
        <el-form-item label="加工柔性" required>
          <el-select v-model="temp.processFlexibility" class="filter-item" >
            <el-option v-for="item in workpieceProcessFlexibleOptions" :key="item.key" :label="item.display_name"
              :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="工艺流程" prop="processInfo" required >
          <el-input v-model="temp.processInfo" type="textarea" placeholder="请输入工件工艺流程" rows="3" />
        </el-form-item>
        <el-form-item label="描述" prop="workpieceDescription">
          <el-input v-model="temp.workpieceDescription" type="textarea" placeholder="请输入描述信息" rows="5" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addWorkpiece">确认</el-button>
      </div>
    </el-dialog>

    <!-- 工件类别表单填写 -->
    <el-dialog v-if="true" :visible.sync="addCategoryFormVisible" title="增加工件类别">
      <el-form ref="addCategoryForm" :rules="rules" :model="mytemp" label-position="right" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <!-- prop 和  v-model 必须保持一致-->
        <el-form-item label="工件类别" prop="categoryName">
          <el-input v-model="mytemp.categoryName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCategoryFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addWorkpieceCategory">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import waves from '@/directive/waves'            // Waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import { fetchSeries } from '@/api/init'
  import { fetchList, updateWorkpiece, addWorkpiece, addWorkpieceCategory } from '@/api/workpiece'
  const workpieceStatusOptions = [
    { key: 0, display_name: '禁止' },
    { key: 1, display_name: '可用' }
  ]
  const workpieceProcessFlexibleOptions = [
    { key: 0, display_name: '否' },
    { key: 1, display_name: '是' }
  ]

  // 
  const calendarTypeKeyValue = workpieceStatusOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  const calendarTypeKeyValueProcess = workpieceProcessFlexibleOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    // 分页组件
    components: { Pagination },
    // 按钮波浪样式
    directives: {
      waves
    },
    // 
    filters: {
      // 按钮样式图标
      statusFilter4Flexibility(status) {
        const statusMap = {
          0: 'info',
          1: 'success',
        }
        return statusMap[status]
      },
      statusFilter(status) {
        const statusMap = {
          0: 'danger',
          1: 'success'
        }
        return statusMap[status]
      },
      // 状态过滤器
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
      // 状态过滤器
      typeFilter4Flexibility(type) {
        return calendarTypeKeyValueProcess[type]
      }
    },
    data() {
      return {
        // 
        tableKey: 0,
        // 工件类别

        // 封装所有条查询的数据
        list: null,
        // 总查询条数
        total: 0,
        // 
        listLoading: true,
        // 封装的查询条件对象
        listQuery: {
          page: 1,
          limit: 5,
          workpieceId: undefined,
          workpieceName: undefined,
          workpieceCategoryId: undefined,
          workpieceStatus: undefined,
          processFlexibility: undefined,
          orderBy: undefined
        },
        workpieceStatusOptions,
        workpieceProcessFlexibleOptions,
        // 临时存储表单的修改数据
        // 
        temp: {
          workpieceId: undefined,
          processInfoId: undefined,
          workpieceCategoryId: undefined,
          workpieceDescription: undefined,
          workpieceImg: undefined,
          workpiecePrice: undefined,
          workpieceStatus: undefined,
          workpieceName: undefined,
          createTime: undefined,
          updatedTime: undefined,
          category: undefined,
          processInfo: undefined,
          processFlexibility: undefined,
          processNum: undefined
        },
        mytemp: {
          categoryName: ""
        },
        // dialogFormVisible：编辑或添加Form的可见性
        dialogFormVisible: false,
        addDialogFormVisible: false,
        addCategoryFormVisible: false,
        // 工件类别列表,字典格式
        options: [],
        // 工件类别名字数组
        categoryNameOptions: [],
        rules: {
          series: [
            { required: true, message: '请选择工件的类别' }
          ],
          workpieceName: [
            { required: true, message: '请输入工件名称', trigger: 'blur' }
          ],
          workpieceImg: [
            { required: true, message: '请上传工件图片', trigger: 'blur' }
          ],
          workpiecePrice: [
            { required: true, message: '请输入工件售卖价格', trigger: 'blur' },
            { type: 'number', message: '售价必须为数字值' }
          ],
          workpieceDescription: [
            { required: false, message: '请输入工件描述' }
          ],
          categoryName: [
            { required: true, message: '请输入工件类别', trigger: 'blur' }
          ],
          processInfo: [
            { required: true, message: '请输入工件加工流程信息', trigger: 'blur' }
          ],
          processFlexibility: [
            { required: true, message: '请输入工件是否柔性加工', trigger: 'blur' }
          ],
          processNum: [
            { required: true, message: '请输入工件的工序数', trigger: 'blur' },
            { type: 'number', message: '工序个数必须为数字值' }
          ],
        },
        downloadLoading: false
      }
    },
    // 创建完 data 等初始化数据后,挂载数据之前
    created() {
      // 获取总记录条数和查询到的记录
      this.getList()
      // // 获取工件的品种，这是固定不变的，类似于数据字典一样
      this.getCategoryOpt()
    },
    methods: {
      getCategoryOpt() {
        // 发送 ajax 请求
        fetchSeries().then(response => {
          // 封装进 options 中
          this.options = response.data.data
          for (const v of this.options) {
            this.categoryNameOptions.push(v.categoryName)
          }
        })
      },
      // 获取brand
      // checkPermission,
      // 查询所有条数据
      getList() {
        // 表示加载 list 数据的状态为 true
        this.listLoading = true
        // 发送 ajax 请求,并携带相应的条件对象,初始化时条件对象为空
        fetchList(this.listQuery).then(response => {
          // response.data 是返回的 Vo 通过浏览器封装的一层对象 {code, msg, data}
          if (response.data.code == 10000) {
            // 后端的 data 中封装了 items 和 total 两个元素
            this.list = response.data.data.items
            this.total = response.data.data.total
          } else {
            // 弹窗显示错误类型
            this.$message({
              // message: response.data.message,
              message: "查询到0条记录！",
              type: 'error'
            })
          }
          this.listLoading = false

          // Just to simulate the time of the request
          // setTimeout(() => {
          //   this.listLoading = false
          // }, 0.5 * 1000)

        })
      },
      categoryFilter(category) {
        for (const v of this.options) {
          // 找到当前品牌的索引
          if (v.categoryId == category) {
            return v.categoryName
          }
        }
        return undefined
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 增加工件信息
      handleAddWorkpiece() {
        // 清空 temp
        this.temp = Object.assign({}, {})
        // 打开表单显示
        this.addDialogFormVisible = true
        // 下一次点击的时候清空表单验证信息
        this.$nextTick(() => {
          this.$refs['addDataForm'].clearValidate()
        })
      },
      // 增加工件类别信息
      handleAddCategory() {
        // 清空 temp
        this.mytemp.categoryName = null
        // 打开表单显示
        this.addCategoryFormVisible = true
        // 下一次点击的时候清空表单验证信息
        this.$nextTick(() => {
          this.$refs['addCategoryForm'].clearValidate()
        })
      },

      addWorkpieceCategory() {
        // this.$refs['addCategoryForm'].validate((valid) => {window.console.log()})
        // 获取表单对象，验证 rules 得到验证的值 valid 为 true 或者 false
        this.$refs['addCategoryForm'].validate((valid) => {
          // 验证通过
          if (valid) {
            // 做安全性校验
            var flag = true
            // 去掉字符串内的所有空格
            // this.temp.workpieceCategory = this.temp.workpieceCategory.replace(/\s*/g, '')
            // 判断工件类别是否已经被注册过
            // for (const v of this.options) {
            //   // 找到当前品牌的索引
            //   if (v.categoryName == this.mytemp.workpieceCategory) {
            //     flag = false
            //   } else {
            //     flag = true
            //   }
            // }
            
            if (flag) {
              addWorkpieceCategory(this.mytemp).then(response => {
                if (response.data.code === 10000) {
                  this.getCategoryOpt()
                  this.$notify({
                    title: '成功',
                    message: '增加成功',
                    type: 'success',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: '错误',
                    message: response.data.message,
                    type: 'error',
                    duration: 2000
                  })
                }
                this.addCategoryFormVisible = false
              })
            } else {
              this.$notify({
                title: '错误',
                message: '该工件类别已经被注册',
                type: 'error',
                duration: 2000
              })
              this.addCategoryFormVisible = false
            }
          }
        })

      },
      addWorkpiece() {
        // 获取表单对象，验证 rules 得到验证的值 valid 为 true 或者 false
        this.$refs['addDataForm'].validate((valid) => {
          // 验证通过
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.processInfoId = 0
            addWorkpiece(tempData).then(response => {
              if (response.data.code === 10000) {
                this.listQuery.orderBy = "createTime desc"
                this.getList()
                this.$notify({
                  title: '成功',
                  message: '增加成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '错误',
                  message: response.data.message,
                  type: 'error',
                  duration: 2000
                })
              }
              this.addDialogFormVisible = false
            })
          }
        })
      },
      // 点击小箭头排序
      sortChange(data) {

        const { prop, order } = data
        if (order === 'ascending') {
          this.listQuery.orderBy = prop + ' asc'

        } else if (order === 'descending') {
          this.listQuery.orderBy = prop + ' desc'
        } else {
          this.listQuery.orderBy = null
        }
        window.console.log(this.listQuery.orderBy)
        this.handleFilter()
      },
      // 执行编辑操作，表格中的一行数据
      handleUpdate(row) {
        // 数据拷贝，备份，Object.assign，浅拷贝
        this.temp = Object.assign({}, row) // copy obj
        // 绑定 data 中实体workpiece的 workpieceCategoryId
        this.temp.category = this.categoryFilter(this.temp.workpieceCategoryId)
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      parseTime,
      // 更新表单
      updateData() {
        // 获取表单对象，验证 rules 得到验证的值 valid 为 true 或者 false
        this.$refs['dataForm'].validate((valid) => {
          // 验证通过
          if (valid) {
            const tempData = Object.assign({}, this.temp)

            updateWorkpiece(tempData).then(response => {
              if (response.data.code === 10000) {
                this.getList()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '错误',
                  message: response.data.message,
                  type: 'error',
                  duration: 2000
                })
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
    }
  }
</script>